﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Aspose.Cells;
using Aspose.Slides;
using Aspose.Slides.Export;
using Aspose.Words;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using OBS;
using OBS.Model;
using SXFramWork.Core;
using SXFramWork.Model;
using SXFramWork.Service;

namespace SXFramWork.API.Controllers.Admin
{
    /// <summary>
    /// 账户管理
    /// </summary>
    public class SysUserController : WebController
    {
        private readonly ISysUserService _userService;
        private readonly IWebHostEnvironment _hostEnvironment;
        private readonly ILoginInfo _loginInfo;
        public SysUserController(ISysUserService sysUserService,IWebHostEnvironment webHostEnvironment,ILoginInfo loginInfo)
        {
            _loginInfo = loginInfo;
            _hostEnvironment = webHostEnvironment;
            _userService = sysUserService;
        }
        /// <summary>
        /// 账户管理列表
        /// </summary>
        /// <param name="model">查询模型</param>
        /// <returns></returns>
        [HttpGet]
        [Menu("账户管理","/admin/sysuser")]
        public async Task<IApiResult> List([FromQuery]UserQueryModel  model)
        {
            return await _userService.Query(model);
        }
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="model">新增模型</param>
        /// <returns></returns>
        [HttpPost]
        [Power("新增")]
        public async Task<IApiResult> Add([FromBody]UserAddModel model)
        {
            return await _userService.Add(model);
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost]
        [Power("删除")]
        [Log]
        public async Task<IApiResult> Delete([FromBody] List<string> ids)
        {
            return await _userService.Delete(ids);
        }
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Power("编辑")]
        public async Task<IApiResult> Update([FromBody]UserUpdateModel model)
        {
            return await _userService.Update(model);
        }
        /// <summary>
        /// 查询单个账户
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        [Power("查询单个账户")]
        public async Task<IApiResult> Get([FromQuery] string id)
        {
            return await _userService.GetById(id);
        }

        /// <summary>
        /// 查询单个账户
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        [Common]     
        public async Task<IApiResult> GetBasic()
        {          
            return await _userService.GetById(_loginInfo.UserId);
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Common]
        public async Task<IApiResult> EditPwd([FromBody]JObject parm)
        {
            return await _userService.EditPwd(parm.Value<string>("oldPassword"), parm.Value<string>("newPassword"));

        }

        /// <summary>
        /// 用户修改基本信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Common]
        public async Task<IApiResult> UpdateBasic([FromForm]UpdateModel_Basic model)
        {
            return await _userService.UpdateBasic(model);
        }
        /// <summary>
        /// pdf预览
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async  Task<IApiResult> GetPdf([FromQuery]string id)
        {
            //try
            //{


            //Loghelper.Default.writelog("测试错误日志");
            ////获取模板文件路径
            //string fileName = Path.Combine(_hostEnvironment.WebRootPath, "files", "Template", "模板.docx");
            //FileInfo info = new FileInfo(fileName);
            //if (!info.Exists)
            //{
            //    return ApiResult.NotOk("附件丢失");
            //}
            //Aspose.Words.LoadOptions opt = new Aspose.Words.LoadOptions();
            //opt.Encoding = Encoding.UTF8;
            //Aspose.Words.Document doc = new Aspose.Words.Document(fileName, opt);

            ////处理sql得到数据
            //List<object> param = new List<object>();
            //param.Add(id);
            //var sql_param = param.ToArray();
            //var res = await _userService.GetUserInfo(id);
            //SysUserEntity obj_data = res.Data;

            ////遍历普通域 插入
            //DocumentBuilder builders = new DocumentBuilder(doc);
            //string[] mailMerge = doc.MailMerge.GetFieldNames();
            //foreach (var item in mailMerge)
            //{
            //    var imageinfo = item.Split(':');
            //    if (imageinfo.Length < 2 || imageinfo[0] != "图片")
            //    {
            //        if (obj_data.ContainProperty(item))
            //        {
            //            builders.MoveToMergeField(item);
            //            var obj_data_val = obj_data.GetValueByProperty(item).To_String();
            //            //解析
            //            builders.Write(StringHelper.HtmlDecode(obj_data_val));

            //        }
            //        continue;
            //    }

            //    //处理图片
            //    var imgname = imageinfo[1];//图片名字
            //    var imgurl = obj_data.GetValueByProperty(imgname).To_String();//图片地址
            //    if (imgurl.Length < 1)
            //        continue;
            //    double width = 0, height = 0;
            //    if (imageinfo.Length > 3)
            //    {
            //        width = imageinfo[2].To_Double();//宽度
            //        height = imageinfo[3].To_Double();//宽度
            //    }

            //    //合并域名和地址
            //    Uri url = new Uri(imgurl);
            //    //获取图片
            //    var bytes = HttpHelper.HttpWebRequestImage(url.ToString());
            //    if (bytes.Length < 1)
            //    {
            //        builders.MoveToMergeField(imgname);
            //        continue;
            //    }
            //    //将插入光标移到指定的图片域
            //    while (builders.MoveToMergeField(item))
            //    {
            //        if (width != 0 || height != 0)
            //            builders.InsertImage(bytes, width, height);
            //        else
            //            builders.InsertImage(bytes);
            //    }

            //}
            //var ss = doc.MailMerge.GetFieldNames();
            //doc.MailMerge.DeleteFields();
            //var docStream = new MemoryStream();
            //doc.Save(docStream, Aspose.Words.SaveFormat.Pdf);
            //Response.Clear();
            //Response.ContentType = "application/pdf";
            //await Response.Body.WriteAsync(docStream.GetBuffer(), 0, docStream.GetBuffer().Length);
            //return ApiResult.Ok();

            // }
            //catch(Exception ex)
            //{
            //    return ApiResult.NotOk();
            //}



            //#region  //预览excel
            //string fileName = Path.Combine(_hostEnvironment.WebRootPath, "files", "Template", "模板excel.xlsx");
            //Aspose.Cells.LoadOptions opt = new Aspose.Cells.LoadOptions(Aspose.Cells.LoadFormat.Xlsx);
            //Aspose.Cells.Workbook wk = new Aspose.Cells.Workbook(fileName, opt);
            //Aspose.Cells.PdfSaveOptions pdfSaveOptions = new Aspose.Cells.PdfSaveOptions();
            //pdfSaveOptions.OnePagePerSheet = true;
            //Aspose.Cells.Worksheet sht = wk.Worksheets[0];//查看文档的sheet0内容  
            //Aspose.Cells.Cells cells = sht.Cells;//获取sheet0的所有单元格  
            //var docStream = new MemoryStream();
            //wk.Save(docStream, pdfSaveOptions);
            //Response.Clear();
            //Response.ContentType = "application/pdf";
            //await Response.Body.WriteAsync(docStream.GetBuffer(), 0, docStream.GetBuffer().Length);

            //return ApiResult.Ok();
            //string fileName = Path.Combine(_hostEnvironment.WebRootPath, "files", "Template", "模板excel.xlsx");
            //FileInfo info = new FileInfo(fileName);
            //if (!info.Exists)
            //{
            //    return ApiResult.NotOk("附件丢失");
            //}
            //Aspose.Cells.LoadOptions opt = new Aspose.Cells.LoadOptions(Aspose.Cells.LoadFormat.Xlsx);


            //Aspose.Cells.Workbook wk = new Aspose.Cells.Workbook(fileName, opt);


            //PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
            //pdfSaveOptions.OnePagePerSheet = true;
            //Worksheet sht = wk.Worksheets[0];//查看文档的sheet0内容  
            //Cells cells = sht.Cells;//获取sheet0的所有单元格  
            //var docStream = new MemoryStream();
            //wk.Save(docStream, pdfSaveOptions);
            //Response.Clear();
            //Response.ContentType = "application/pdf";
            //await Response.Body.WriteAsync(docStream.GetBuffer(), 0, docStream.GetBuffer().Length);
            //return ApiResult.Ok();

            //#endregion



            #region 预览ppt


            //// 创建ObsClient实例
            //ObsClient client = new ObsClient("A353JIAKN3GNQUDUK1HM", "xo8JwM4sDf6nduNtbVXLWaGMOSzKKrZGaSbrVmHG", "obs.cn-south-1.myhuaweicloud.com");
            //// 下载对象
            //GetObjectRequest request = new GetObjectRequest()
            //{
            //    BucketName = "bucket-gd",
            //    ObjectKey = "sys.pptx",
            //};
            //using (GetObjectResponse response = client.GetObject(request))
            //{


            //   // string fileName = Path.Combine(_hostEnvironment.WebRootPath, "files", "Template", "模板ppt.pptx");

            //    using (Aspose.Slides.Presentation pres = new Presentation(response.OutputStream))
            //    {
            //        var docStream = new MemoryStream();
            //        Response.Clear();
            //        Crack();
            //        pres.Save(docStream, Aspose.Slides.Export.SaveFormat.Pdf, new Aspose.Slides.Export.PdfOptions()
            //        {
            //            Compliance = PdfCompliance.PdfA1b
            //        });
            //        Response.ContentType = "application/pdf";
            //        await Response.Body.WriteAsync(docStream.GetBuffer(), 0, docStream.GetBuffer().Length);
            //    }
            //    return ApiResult.Ok();

            //}





            #endregion

            //#region pdf
            ////string fileName = Path.Combine(_hostEnvironment.WebRootPath, "files", "Template", "222.pdf");

            //ObsClient client = new ObsClient("A353JIAKN3GNQUDUK1HM", "xo8JwM4sDf6nduNtbVXLWaGMOSzKKrZGaSbrVmHG", "obs.cn-south-1.myhuaweicloud.com");
            //// 下载对象
            //GetObjectRequest request = new GetObjectRequest()
            //{
            //    BucketName = "bucket-gd",
            //    ObjectKey = "测试文件上传/222.pdf",
            //};
            //GetObjectResponse response = client.GetObject(request);
            //var docStream = new MemoryStream();
            //using (var pdfDocument = new Aspose.Pdf.Document(response.OutputStream))
            //{
            //    pdfDocument.Save(docStream);
            //}
            //Response.Clear();
            //Response.ContentType = "application/pdf";
            //await Response.Body.WriteAsync(docStream.GetBuffer(), 0, docStream.GetBuffer().Length);
            //return ApiResult.Ok();

            //#endregion

            ////txt
            //string fileName = Path.Combine(_hostEnvironment.WebRootPath, "files", "Template", "笔记.txt");
            //string outData = "";
            ////处理读取txt乱码
            //Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            //StreamReader sr = new StreamReader(fileName, Encoding.GetEncoding(0));
            //outData = sr.ReadToEnd();
            //sr.Close();
            //Response.WriteAsync(string.Format("<PRE class='txt-content'>{0}</PRE>", outData.Replace("<", "&lt;")), Encoding.GetEncoding(0)).Wait();
            //return ApiResult.Ok();

            //string fileName = Path.Combine(_hostEnvironment.WebRootPath, "files", "Template", "模板.docx");
            //FileInfo info = new FileInfo(fileName);
            //if (!info.Exists)
            //{
            //    return ApiResult.NotOk("附件丢失");
            //}
            //Aspose.Words.LoadOptions opt = new Aspose.Words.LoadOptions();
            //opt.Encoding = Encoding.UTF8;
            //Aspose.Words.Document doc = new Aspose.Words.Document(fileName, opt);

            //var docStream = new MemoryStream();
            //doc.Save(docStream, Aspose.Words.SaveFormat.Pdf);
            //Response.Clear();
            //Response.ContentType = "application/pdf";
            //await Response.Body.WriteAsync(docStream.GetBuffer(), 0, docStream.GetBuffer().Length);
            //return ApiResult.Ok();

            //------------ppt
            //string fileName = Path.Combine(_hostEnvironment.WebRootPath, "files", "Template", "模板ppt.pptx");
            //using (Aspose.Slides.Presentation pres = new Aspose.Slides.Presentation(fileName))
            //{
            //    var docStream = new MemoryStream();
            //    Response.Clear();
            //    Crack();
            //    pres.Save(docStream, Aspose.Slides.Export.SaveFormat.Pdf, new Aspose.Slides.Export.PdfOptions()
            //    {
            //        Compliance = Aspose.Slides.Export.PdfCompliance.PdfA1b
            //    });
            //    Response.ContentType = "application/pdf";
            //    Response.Body.WriteAsync(docStream.GetBuffer(), 0, docStream.GetBuffer().Length);
            //}
            //-----excel
            //string fileName = Path.Combine(_hostEnvironment.WebRootPath, "files", "Template", "模板excel.xlsx");
            //Aspose.Cells.LoadOptions opt = new Aspose.Cells.LoadOptions(Aspose.Cells.LoadFormat.Xlsx);
            //Aspose.Cells.Workbook wk = new Aspose.Cells.Workbook(fileName, opt);
            //Aspose.Cells.PdfSaveOptions pdfSaveOptions = new Aspose.Cells.PdfSaveOptions();
            //pdfSaveOptions.OnePagePerSheet = true;
            //Aspose.Cells.Worksheet sht = wk.Worksheets[0];//查看文档的sheet0内容  
            //Aspose.Cells.Cells cells = sht.Cells;//获取sheet0的所有单元格  
            //var docStream = new MemoryStream();
            //wk.Save(docStream, pdfSaveOptions);
            //Response.Clear();
            //Response.ContentType = "application/pdf";
            //Response.Body.WriteAsync(docStream.GetBuffer(), 0, docStream.GetBuffer().Length);

            //----word
            //string fileName = Path.Combine(_hostEnvironment.WebRootPath, "files", "Template", "模板.docx");
            //Aspose.Words.LoadOptions opt = new Aspose.Words.LoadOptions();
            //opt.Encoding = Encoding.UTF8;
            //Aspose.Words.Document doc = new Aspose.Words.Document(fileName, opt);
            //var docStream = new MemoryStream();
            //doc.Save(docStream, Aspose.Words.SaveFormat.Pdf);
            //Response.Clear();
            //Response.ContentType = "application/pdf";
            //Response.Body.WriteAsync(docStream.GetBuffer(), 0, docStream.GetBuffer().Length);
            //txt
            //string fileName = Path.Combine(_hostEnvironment.WebRootPath, "files", "Template", "excelhelper.txt");
            //string outData = "";
            ////处理读取txt乱码
            //Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            //StreamReader sr = new StreamReader(fileName, Encoding.GetEncoding(0));
            //outData = sr.ReadToEnd();
            //sr.Close();
            //Response.WriteAsync(string.Format("<PRE class='txt-content'>{0}</PRE>", outData.Replace("<", "&lt;")), Encoding.GetEncoding(0)).Wait();
            //------图片
            string fileName = Path.Combine(_hostEnvironment.WebRootPath, "files", "Template", "捕获.jpg");
         
            System.Drawing.Image srcImage = System.Drawing.Image.FromFile(fileName);
            int h = srcImage.Height;
            int w = srcImage.Width;

            // Initialize new Document
            Aspose.Pdf.Document doc = new Aspose.Pdf.Document();
            Aspose.Pdf.Page page = doc.Pages.Add();
            Aspose.Pdf.Image image = new Aspose.Pdf.Image();
            image.File = (fileName);

            // Set page dimensions
            page.PageInfo.Height = (h);
            page.PageInfo.Width = (w);
            page.PageInfo.Margin.Bottom = (0);
            page.PageInfo.Margin.Top = (0);
            page.PageInfo.Margin.Right = (0);
            page.PageInfo.Margin.Left = (0);
            page.Paragraphs.Add(image);
            var docStream = new MemoryStream();
            // Save output PDF
            doc.Save(docStream,Aspose.Pdf.SaveFormat.Pdf);
            Response.Clear();
            Response.ContentType = "application/pdf";
            Response.Body.WriteAsync(docStream.GetBuffer(), 0, docStream.GetBuffer().Length);
            return ApiResult.Ok();
        }
        //去掉水印
        public static void Crack()//使用前调用一次即可
        {
            new Aspose.Slides.License().SetLicense(new MemoryStream(Convert.FromBase64String("PExpY2Vuc2U+CiAgPERhdGE+CiAgICA8TGljZW5zZWRUbz5TdXpob3U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d1ZDcnp6MytVYk9iQjRYUndTZWxsTFdXeXNDL0haTDNpN01SMC9jZUFxaVZFOU0rWndOQkR4RnlRbE9uYTFQajhQMzhzR1grQ3ZsemJLZFZPZXk1S3A2dDN5c0dqYWtaL1E9PC9TaWduYXR1cmU+CjwvTGljZW5zZT4=")));
        }
        /// <summary>
        /// excel导出
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Power("excel导出")]
        public IActionResult ExportExcel()
        {
            var dt = _userService.QueryUserDTable().Result;
            //if (dt == null)
            //throw new Exception("没有需要导出的数据！");
            string fileName =DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
            var ms = new MemoryStream();
            var workbook = ExcelHelper.ExportExcelHSSF(dt, "账号,角色,真实姓名,性别,电话,邮箱,地址");
            workbook.Write(ms);
            ms.Flush();
            ms.Seek(0, System.IO.SeekOrigin.Begin);
            var buffer = ms.GetBuffer();
            return File(buffer, "application/vnd.ms-excel", fileName);
        }
        /// <summary>
        /// Excel导入
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Power("excel导入")]
        public async Task<IApiResult> ImportExcel([FromForm]IFormFile file)
        {
            return await _userService.ImportData(file);
        }

        /// <summary>
        /// 下载excel模板
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Power("下载数据模板")]
        public async Task<ActionResult> DownLoadExcel()
        {
            string fileName = Path.Combine(_hostEnvironment.WebRootPath, "files", "Template","importuser.xlsx");
            return await Task.Run(()=> PhysicalFile(fileName, "application/octet-stream", HttpUtility.UrlEncode("模板.xlsx", Encoding.UTF8), true));          
        }
    }
}